package com.puppet.controller;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.puppet.config.MinioConfig;
import com.puppet.constant.BaseController;
import com.puppet.constant.PageData;
import com.puppet.constant.Result;
import com.puppet.constant.UploadImgConstant;
import com.puppet.entity.Trainer;
import com.puppet.entity.pojo.dto.TrainerDTO;
import com.puppet.service.ITrainerService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 培训师 前端控制器
 * </p>
 *
 * @author puppet
 * @since 2024-09-26
 */
@RestController
@RequestMapping("/trainer")
@CrossOrigin
public class TrainerController extends BaseController {

    @Qualifier("trainerServiceImpl")
    @Autowired
    ITrainerService trainerService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    MinioConfig minioConfig;


    @PostMapping("/getTrainersByPage/{pageNum}/{pageSize}")
    public Result getTrainersByPage(
            @RequestBody TrainerDTO trainerDTO,
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize
    ) {
        Page<Trainer> p = new Page<>(pageNum, pageSize);


//  条件构造器
        QueryWrapper<Trainer> wrapper = new QueryWrapper<>();
        if (trainerDTO != null) {
            if (trainerDTO.getName() != null && (!trainerDTO.getName().trim().equals(""))) {
                wrapper.like("name", trainerDTO.getName()); // 确保 "name" 是 Trainer 表中的列名
            }
            if (trainerDTO.getLevel() != null) {
                wrapper.eq("level", trainerDTO.getLevel()); // 修正为 "level" 以匹配数据库列
            }
            if (trainerDTO.getCreateTimeStart() != null) {
                wrapper.ge("create_time", trainerDTO.getCreateTimeStart()); // 修正为实际的列名
            }
            if (trainerDTO.getCreateTimeEnd() != null) {
                wrapper.le("create_time", trainerDTO.getCreateTimeEnd()); // 修正为实际的列名
            }
        }

        Page<Trainer> page = trainerService.page(p, wrapper);

        PageData myPage = new PageData(page.getTotal(), page.getRecords());
        return this.toDataResult(myPage);

    }

    //新增、修改
    //
    @Transactional
    @PostMapping("/saveOrUpdateTrainer")
    public Result saveOrUpdateTrainer(@RequestBody Trainer trainer) {
        boolean b = trainerService.saveOrUpdate(trainer);
        if (b) {
            // 动态获得桶名称
            String bname = minioConfig.getBuketName();
            //if (trainer.getAvatar() != null && !trainer.getAvatar().isEmpty()) {}
                int start = trainer.getAvatar().indexOf(bname) + bname.length() + 1;
                int end = trainer.getAvatar().indexOf("?");


                String imgName = trainer.getAvatar().substring(start, end);
                // 将最终的有效图片名存储到 Redis中
                stringRedisTemplate.opsForSet().add(UploadImgConstant.saveImg, imgName);
               // http://127.0.0.1:9000/wnxt/f479c?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=e9igr

        }
        return this.success2(b);
    }


    //根据id查询Trainer信息
    @GetMapping("/getTrainerById/{id}")
    public Result getTrainerById(@PathVariable("id") String id) {
        Trainer trainer = trainerService.getById(id);
        return this.toDataResult(trainer);
    }

    //删除培训师 逻辑删除
    @DeleteMapping("/deleteTrainerById/{id}")
    public Result deleteTrainerById(@PathVariable("id") String id) {
        boolean b = trainerService.removeById(id);
        return this.success2(b);
    }

    //导出
    @GetMapping("download")
    public Result download(HttpServletResponse response) throws IOException {
        try {

            List<Trainer> ts = trainerService.list();
            // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("培训师", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), Trainer.class).sheet("模板").doWrite(ts);
        } catch (IOException e) {
            return this.toDataResult("导出失败");
        }
        return this.success();
    }
}
